<script>
import Modal from 'ant-design-vue/es/modal/index.js';
import { UploadOutlined } from '@ant-design/icons-vue';
import { handleCommonRes } from '../utils/resolver.js';
import { uploadFiles } from '../api/index.js';

const uploadAction = async ({ file, filePath }) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('filePath', filePath);
  try {
    return await uploadFiles(formData);
  } catch (e) {
    console.log(e);
  }
};

export default {
  name: 'async-import-button',
  components: { UploadOutlined },
  emits: ['error', 'success'],
  props: {
    /*
     * api：需要返回轮训的 id
     * */
    api: { type: Function, default: undefined },
    /*
     * pollingApi:
     * 需要返回 { ok: Boolean 完成/未完成, success: Boolean 成功/失败, msg: String 成功消息， error: String 失败消息 }
     * */
    pollingApi: { type: Function, default: undefined },
    pollingTimeout: { type: Number, default: 10 * 1000 },
    fileSavePath: { type: String, default: '/import-files' },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    async polling(params) {
      if (typeof this.pollingApi === 'function') {
        let data = null;
        try {
          data = await this.pollingApi(params);
        } catch (e) {
          data = null;
        }
        if (typeof data !== 'object' || !data || !data.ok) {
          setTimeout(() => this.polling(params), this.pollingTimeout);
          return;
        }
        Modal[data.success ? 'success' : 'error']({
          title: `导入${data.success ? '成功' : '失败'}！${data.success ? '页面将自动刷新~~' : ''}`,
          content: data.success ? data.msg : data.error,
          onOk: () => data.success && this.$emit('success'),
        });
        setTimeout(() => {
          if (this.modal && typeof this.modal.destroy === 'function') {
            this.modal.destroy();
          }
        }, 300);
      }
    },
    async onchange({ file }) {
      if (!file || !(file instanceof File)) return;
      this.loading = true;
      let id;
      let params = { file, filePath: this.fileSavePath };
      let { url } = await handleCommonRes(uploadAction, params, {
        defaultValue: {},
        onFail: () => (this.loading = false),
      });
      if (!url) {
        this.$message.error('上传文件失败！');
        this.loading = false;
        this.$emit('error');
        return;
      }
      if (typeof this.api !== 'function') {
        this.loading = false;
        return;
      }
      try {
        id = await this.api(url);
      } catch (e) {
        id = null;
      }
      if (!id) {
        this.$message.error('导入失败！');
        this.loading = false;
        this.$emit('error');
        return;
      }
      this.modal = Modal.success({
        title: '正在后台导入中',
        content: '稍后请注意查看页面提示消息~~',
      });
      this.polling(id).catch(() => {});
      this.loading = false;
    },
  },
};
</script>

<template>
  <a-upload :disabled="loading" :show-upload-list="false" :before-upload="() => false" @change="onchange">
    <a-button type="primary" :loading="loading">
      <slot>
        <upload-outlined></upload-outlined>
        <span>导入</span>
      </slot>
    </a-button>
  </a-upload>
</template>

<style scoped lang="less"></style>
